#!/usr/bin/env python3.3

#
#  Filename: e60.py
#  Author  : lukas singer
#
#  Comment : Created by createSolution.sh
#

#
#ACHTUNG!!!
#DIESER CODE SCHLÄFT!!!
#THIS CODE SLEEPS!!!
#

#import euler
from euler import primeSieve, isPrime

def concateNum(n1,n2):
  nx=1
  while nx<n2:
    nx*=10
  return n1*nx+n2

def isConcatenablePrimePair(p1,p2):
  return (checkPrime(concateNum(p1,p2)) and checkPrime(concateNum(p2,p1)))

def checkPrime(p):
  if p<maxprime:
    return p in primes
  else:
    return isPrime(p)

maxprime=1000000
primes=primeSieve(maxprime)
def pe60():
  ps=primeSieve(10000)
  print('sieve done!')
  minsum=int(1e6)
  ps.remove(2)
  ps.remove(5)
  for i in range(len(ps)-1):
    for j in range(i+1,len(ps)-1):
      if sum([ps[i],ps[j]])>minsum:break
      if isConcatenablePrimePair(ps[i],ps[j]):
        for k in range(j+1,len(ps)-1):
          if sum([ps[i],ps[j],ps[k]])>minsum:break
          if isConcatenablePrimePair(ps[i],ps[k]) and \
             isConcatenablePrimePair(ps[j],ps[k]): 
            for l in range(k+1,len(ps)-1):
              if sum([ps[i],ps[j],ps[k],ps[l]])>minsum:break
              if isConcatenablePrimePair(ps[i],ps[l]) and \
                 isConcatenablePrimePair(ps[j],ps[l]) and \
                 isConcatenablePrimePair(ps[k],ps[l]):
                for m in range(l+1,len(ps)-1):
                  p=[ps[i],ps[j],ps[k],ps[l],ps[m]]
                  if sum(p)>minsum:break
                  if isConcatenablePrimePair(ps[i],ps[m]) and \
                     isConcatenablePrimePair(ps[j],ps[m]) and \
                     isConcatenablePrimePair(ps[k],ps[m]) and \
                     isConcatenablePrimePair(ps[l],ps[m]): 
                    minsum=sum(p)
                    print(p,minsum)
  print(minsum)

if __name__=="__main__":
  print('slowest possible implementation ;-(')
  pe60()

